<template>
  <div class="innerContainer">
    <common-title>
      <template #expand>
      </template>
    </common-title>
    <div class="innerPane">
      <div class="filterArea">
        <el-form :inline="true" :model="filterForm" class="demo-form-inline">
          <el-form-item label="断面编码">
            <el-select v-model="searchForm.task" placeholder="请选择断面编码" @change="handleChange">
              <el-option v-for="item in taskOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>

          <el-form-item label="上传时间">
            <el-date-picker v-model="range" type="datetimerange" start-placeholder="开始时间"
              value-format="YYYY-MM-DD HH:mm:ss" end-placeholder="结束时间" />
          </el-form-item>

          <el-form-item label="同步状态">
            <el-select v-model="searchForm.isSync" placeholder="请选择同步状态">
              <el-option v-for="item in synced" :key="item.val" :label="item.label" :value="item.val" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button plain type="primary" @click="search">查询</el-button>
            <el-button plain @click="onClear">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-table :data="tableData" border row-key="id" style="width: 100%;  " row-class-name="fixed-row"
        :cell-style="{ textAlign: 'center' }">
        <el-table-column type="index" width="50" label="序号" />
        <el-table-column header-align="center" prop="fileName" label="文件名称" width="160" />
        <el-table-column header-align="center" prop="fileSuffix" label="文件类型" width="120" />
        <el-table-column header-align="center" prop="fileSize" label="文件大小" width="100" />
        <el-table-column header-align="center" prop="filePath" label="文件路径">
          <template #default="scope">
            <el-link type="primary" :underline="false" @click.prevent="downloadFile(scope.row)">
              {{ scope.row.filePath }}
            </el-link>
          </template>
        </el-table-column>

        <el-table-column header-align="center" prop="isSynced" label="同步状态" width="120">
          <template #default="scope">
            <el-tag :type="toSyncTag(scope.row)" effect="dark">
              {{ toSyncText(scope.row) }}
            </el-tag>
          </template> </el-table-column>
        <el-table-column header-align="center" prop="syncTime" label="同步时间" />


        <el-table-column header-align="center" prop="isSynced" label="解包状态" width="120">
          <template #default="scope">
            <el-tag :type="toUnpackTag(scope.row)" effect="dark">
              {{ toUnpackText(scope.row) }}
            </el-tag>
          </template> </el-table-column>

        <el-table-column header-align="center" prop="uploadTime" label="上传时间" />

        <el-table-column label="操作" header-align="center" width="140" prop="col9">
          <template #default="scope">
            <el-link type="primary" size="small" @click="handleUnpack(scope.$index, scope.row)">解包</el-link>

            <el-link type="primary" size="small" @click="openView(scope.$index, scope.row)">详情</el-link>
          </template>
        </el-table-column>


      </el-table>
      <!-- 分页 -->
      <el-pagination class="pagination" :current-page="searchForm.current" :page-size="searchForm.size"
        :page-sizes="[10, 50, 100, 200]" layout="->,total, sizes, prev, pager, next, jumper" :total="total"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
  </div>

  <detail-setting ref="detailSetting" />

  <propconfig-view ref="propcofigObj"></propconfig-view>
</template>

<script setup>
defineOptions({
  name: "datamonitoringlist"
})

import CommonTitle from "@/components/CommonTitle.vue";
import { onMounted, reactive, ref, watch } from "vue";
import { useRouter } from "vue-router";

import { uploadSyncLogsList, clienttaskList, uploadFileUnpack } from "@/utils/requests";
import { de } from "element-plus/es/locales.mjs";

import { ElMessage, ElTree, ElButton, ElMessageBox } from "element-plus";

const router = useRouter();

// 用户数据
let tableData = ref([]);

let taskOptions = ref({});


let total = ref(0);

const range = ref([])

let synced = ref([
  { val: 0, label: "未同步", type: 'warning' },
  { val: 1, label: "已同步", type: 'success' },
  { val: -1, label: "同步失败", type: 'danger' },
    { val: -2, label: "同步失败", type: 'danger' }
]);

let unpacked = ref([
  { val: 0, label: "未解包", type: 'warning' },
  { val: 1, label: "已解包", type: 'success' }
])


// 搜索条件
const searchForm = reactive({
  current: 1,
  size: 10,
  isSync: null,
  startDate: '',
  endDate: '',
  task: ""
});

// Dom 挂载之后
onMounted(async () => {
  await requestTaskList();

  await search();
});


watch(
  () => [searchForm.startDate, searchForm.endDate],
  ([s, e]) => { range[0] = s; range[1] = e; },
  { immediate: true }
)

watch(range, ([s, e]) => {
  searchForm.startDate = s
  searchForm.endDate = e
}, { immediate: true })



const requestTaskList = async () => {
  let res = await clienttaskList({
    current: 1,
    size: 200
  });
  taskOptions.value = res?.records?.map(item => ({
    label: item.taskName,
    value: item.taskName
  }))

  if (taskOptions.value && taskOptions.value.length > 0 && !searchForm.task) {
    searchForm.task = taskOptions.value[0].value;
  };
};

const handleChange = (val) => {
  searchForm.task = val;
  search();
};

const onClear = () => {
  searchForm.isSync = null;
  searchForm.startDate = '';
  searchForm.endDate = '';
  search();
};

const handleSizeChange = (size) => {
  searchForm.size = size;
  searchForm.current = 1;
  search();
};
const handleCurrentChange = (current) => {
  searchForm.current = current;
  search();
};

const search = () => {
  uploadSyncLogsList(searchForm).then((res) => {
    tableData.value = res.records;
    total.value = res.total;
  });
};

const toSyncTag = (rowData) => {
  return synced.value.find(item => item.val === rowData.isSynced)?.type || "info";
};

const toSyncText = (rowData) => {
  return synced.value.find(item => item.val === rowData.isSynced)?.label || "";
};

const toUnpackTag = (rowData) => {
  return unpacked.value.find(item => item.val === rowData.isUnpack)?.type || "info";
};

const toUnpackText = (rowData) => {
  return unpacked.value.find(item => item.val === rowData.isUnpack)?.label || "";
};

// 文件下载方法
const downloadFile = (row) => {
  if (!row.filePath) return;
  // 假设 filePath 是后端可直接访问的 URL，否则需拼接前缀
  const url = row.fileDownloadUrl;
  const a = document.createElement('a');
  a.href = url;
  a.download = row.fileName || '';
  a.target = '_blank';
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
};

const handleUnpack = (index, row) => {

  ElMessageBox.confirm("是否确认解压此文件？", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    // 确认解包逻辑
    uploadFileUnpack({ task: encodeURIComponent(searchForm.task), id: row.id }).then(() => {
      ElMessage.success("解包成功");
      search();
    }).catch(() => {
      ElMessage.error("解包失败");
    });

  }).catch(() => {
    // 取消解包逻辑
  });
}

// 详情查看弹窗
const openView = (index, row) => {
  router.push({
    path: "/sync/details",
    query: {
      task: searchForm.task,
      fileName: row.fileName,
      id: row.id,
    },
  });
};

const propcofigObj = ref();

const openPropsConfig = () => {
  propsConfigObj.value.openDialog();
};
</script>

<style scoped>
.filterArea {
  display: flex;
  justify-content: space-between;
  padding-top: 10px;
}

.filterArea .el-select {
  width: 120px;
}

.el-table .el-link {
  margin-right: 10px;
}
</style>
